package xj.util.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeListener;

public class OptionDialog extends JDialog {

  public OptionDialog(JFrame owner, 
		      ChangeListener listener,
		      OptionPanel[] options) {
    this(owner, null, listener, options);
  }

  public OptionDialog(JFrame owner, 
		      String title, 
		      ChangeListener listener,
		      OptionPanel[] options) {
    super(owner, "Options");
    this.listener = listener;
    this.options = options;

    getContentPane().setLayout(new BorderLayout());

    if (title != null) {
      JLabel titleLabel = new JLabel(title);
      titleLabel.setBackground(Color.white);
      titleLabel.setFont(titleFont);
      getContentPane().add(titleLabel, BorderLayout.NORTH);
    }

    if (options != null && options.length > 0) {
      if (options.length == 1) {
	if (options[0] != null) {
	  getContentPane().add(options[0], BorderLayout.CENTER);
	  options[0].setDialog(this);
	  options[0].setListener(listener);
	}
      } else {
	JTabbedPane tabbedPane = new JTabbedPane();
	getContentPane().add(tabbedPane, BorderLayout.CENTER);
	for (int i = 0; i < options.length; i++) {
	  if (options[0] != null) {
	    tabbedPane.addTab(options[i].getName(), options[i]);
	    options[i].setDialog(this);
	    options[i].setListener(listener);
	  }
	}
      }
    }

  }

  public void setOptions() {
    if (options != null) {
      for (int i = 0; i < options.length; i++) {
	if (options[i] != null) {
	  options[i].setOption();
	}
      }
    }
  }

  public void showOptionDialog() {
    pack();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension dialogSize = getSize();
    setLocation(screenSize.width / 2 - dialogSize.width / 2, 
		screenSize.height / 2 - dialogSize.height / 2);
    // setAlwaysOnTop(true);
    setVisible(true);
  }

  protected ChangeListener listener;

  protected OptionPanel[] options;

  protected static Font titleFont = new Font("SansSerif", Font.BOLD, 24);

}
